package com.deng.schedules;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deng.entity.Post;
import com.deng.service.PostService;
import com.deng.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;

@Component
@EnableScheduling
public class ViewCountSyncTask {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    PostService postService;
    @Scheduled(cron="0/5 * * * * *")//每5秒同步一次
    public void task(){
        Set<String> keys = redisTemplate.keys("rank:post:*");

        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if(redisUtil.hHasKey(key, "post:viewCount")){
                //获取文章id
                ids.add(key.substring("rank:post:".length()));
            }
        }

        if(ids.isEmpty()) return;

        // 需要更新阅读量的文章，缓存中有浏览量的文章
        List<Post> posts = postService.list(new QueryWrapper<Post>().in("id", ids));
        //更改文章的阅读量
        posts.stream().forEach((post) ->{
            //从缓存中获取阅读量
            Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        });

        if(posts.isEmpty()) return;
        //持久化到数据库
        boolean isSucc = postService.updateBatchById(posts);
        //持久化成功后删除缓存
        if(isSucc) {
            ids.stream().forEach((id) -> {
                redisUtil.hdel("rank:post:" + id, "post:viewCount");
                System.out.println(id + "---------------------->同步成功");
            });
        }else{
            System.out.println("============>同步失败");
        }
    }
}
